﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using Microsoft.Ajax.Utilities;
using wne.code;
using wne.core;
using wne.core.Interface;
using wne.models;
using wne.Models;
using wne.models.Filter;

namespace wne.Controllers
{
    [Authorize]
    public class AdminController : Controller
    {
         private AdminFacade facade;
         public AdminController()
         {
             facade = new AdminFacadeSql();
         }
         #region Groups

         public ActionResult AllGroups(string searchString = "", int start = 0, int count = 0, int OrderNum = 2)
         {
             var model = facade.GetFilteredGroupSmall(new GroupSmallFilter
             {
                 IsOrderDesc = OrderNum % 2 == 0,
                 OrderEnum = (GroupSmallOrderEnum)( (OrderNum +1 )/ 2),
                 Count = null,
                 StartIndex = null,
                 SearchString = searchString
             });
             ViewBag.OrderNum = OrderNum;
             ViewBag.SearchString = searchString;
             ViewBag.Start = start;
             ViewBag.Count = count;
             return View(model);
         }
 
         [HttpPost]
         public ActionResult AddGroup(string name)
         {
             //return Redirect("/Admin/EditGroup?id="+ facade.AddGroup(name));


             if (facade.GroupNotExists(name))
             {
                 return Redirect("/Admin/EditGroup?id=" + facade.AddGroup(name));
             }
             else
             {
                 return Redirect("AllGroups");
             }
         }
 
         [HttpPost]
         public JsonResult DeleteGroup(int id)
         {
             facade.RemoveGroup(id);
             return new JsonResult();
         }
         public ActionResult EditGroup(int id=0)
         {
             var model = facade.GetGroupById(id);
             return View(model);
         }

        [HttpPost]
        public JsonResult UpdateGroup(GroupModel model)
        {
            model.Fields.ForEach(x =>
            {
                while (x.AvaliableValues.Any(y => string.IsNullOrEmpty(y.Value)))
                    x.AvaliableValues.Remove(x.AvaliableValues.First(y => string.IsNullOrEmpty(y.Value)).Key);
            });
            facade.UpdateGroup(model);
            return new JsonResult();
        }
        public ActionResult GetAvailableParents(List<int> ids, int groupId)
        {
            ViewBag.ParentList = facade.GetAvaliableParents(groupId);
            return View("pAddParentToGroup");
        }

        public ActionResult GetGroupFieldRow(FieldModel model)
        {
            if (model==null)
                model = new FieldModel();
            return View("PGroupRow",model);
        }
        [HttpPost]
        public JsonResult AddParentForGroup(int pIdParent, int pIdGroup)
         {
             facade.AddParentForGroup(pIdParent, pIdGroup);
             return new JsonResult();
         }
        [HttpPost]
        public JsonResult DelParentForGroup(int pIdParent, int pIdGroup)
        {
            facade.DeleteParentForGroup(pIdParent, pIdGroup);
            return new JsonResult();
        }
        

            


         #endregion
         
        #region Users

        public ActionResult AllUsersPage()
        {
            ViewBag.AllGroups = facade.GetAllGroups();
            ViewBag.SelectedGroup = -1;
            return View(facade.GetFilteredUsers(new UserFilter { StartIndex = null, Count = null, OrderEnum = UserOrderEnum.UserName, IsOrderDesc = false, IdGroup = -1, SearchString = ""}));
        }
        public ActionResult AllUsersPartial(int groupId = -1,string searchString = "", int start = 0, int count = 0, int orderNum = 1)
        {
            var model = facade.GetFilteredUsers(new UserFilter
            {
                Count = null,
                StartIndex = null,
                OrderEnum = UserOrderEnum.UserName,
                IsOrderDesc = orderNum==2,
                SearchString = searchString,
                IdGroup = groupId
            });
            ViewBag.SelectedGroup = groupId != -1 ? groupId : -1;
            return View("pAllUsers",model);
        }

        public ActionResult AddUser()
        {
            return View();
        }
    [HttpPost]
        public ActionResult AddUser(UserModel model)
        {
            if (facade.UserNotExists(model.UserName))
                return Redirect("EditUser?id=" + facade.AddUser(model));
            else
            {
                return Redirect("AllUsersPage");
            }
        }
        public ActionResult EditUser(int? id)
        {
            UserModel usermodel = new UserModel();
            usermodel.Id = -1;
            if (id != null)
            {
                usermodel = facade.GetUserById((int)id);
            }
            if (usermodel == null)
                usermodel = new UserModel();
            Session["qqq"] = usermodel;
            return View(usermodel);
        }
        [HttpPost]
        public ActionResult EditUser(UserModel model,int? id)
        {
            //return View(model);
            var tempModel = (UserModel)Session["qqq"];
            if (model.Id == -1)
                facade.AddUser(model);
            else
                facade.UpdateUser(model);
            /*{
                if (facade.AddUser(model) == -1) return View(model);
            }
            facade.UpdateUser(model);*/
            
            //UserModel new_model = new UserModel();
            //new_model = facade.GetUserById((int)model.Id);


            //return View(new_model); // в случае ошибок возвращает ту же самую модель, нужно заного заполнить селекты, а лучше прописать в вьюве
                                // через хиддены чтобы заполнялись сами - гавнокод, но прокатит!


            return Redirect("EditUser?id=" + model.Id);
        
        }

        public ActionResult EditUserEditGroup(int id)
        {
            UserModel model = facade.GetUserWithGroupsList(id);

            return View(model);


            
            ////тесты
            //UserModel usermodel = new UserModel();
            //usermodel.Id = 17;
            //usermodel.UserName = "FUCK";
            //usermodel.Surname = "F";
            //usermodel.FirstName = "U";
            //usermodel.SecondName = "CK";
            //usermodel.Phone = "1234567";
            //usermodel.UserEmail = "e@ma.il";
            //usermodel.UserBd = "2014-03-17";
            //usermodel.UserGroups = new List<GroupModel>
            //    {
            //        new GroupModel
            //        {
            //            Id = 10,
            //            Name = "qqq",
            //            Fields = new List<FieldModel>
            //            {
            //                new FieldModel { FieldId = 1, Name = "field1", Type = FieldTypeEnum.String, Value = "asd", UserCanEdit = true, Mandatory = true },
            //                new FieldModel { FieldId = 2, Name = "field2", Type = FieldTypeEnum.Numeric, Value = "2", UserCanEdit = true, Mandatory = false },
            //                new FieldModel { FieldId = 3, Name = "field3", Type = FieldTypeEnum.Date, Value  = "2014-03-07", UserCanEdit = false, Mandatory = true },
            //                new FieldModel { FieldId = 4, Name = "field4", Type = FieldTypeEnum.Bool, Value="False", UserCanEdit = false, Mandatory = false },
            //                new FieldModel { FieldId = 5, Name = "field5", Type = FieldTypeEnum.OneOf, AvaliableValues = new Dictionary<int,string>{{1,"aewq"},{2,"ad"}} , UserCanEdit = false, Mandatory = true },
            //                new FieldModel { FieldId = 6, Name = "field6", Type = FieldTypeEnum.ManyOf, AvaliableValues = new Dictionary<int,string>{{1,"aewq"},{2,"ad"},{3,"qwe"}} , UserCanEdit = false, Mandatory = false }
            //            }

            //        }
            //    };
            //return View(model);
        }

        [HttpPost]
        public JsonResult EditUserEditGroup_DelGroup(int userId, int groupId)
        {
            facade.RemoveGroupFromUser(userId, groupId);
            return new JsonResult();
        }
        [HttpPost]
        public JsonResult EditUserEditGroup_AddGroup(int userId, int groupId)
        {
            facade.AddGroupToUser(userId, groupId);
            return new JsonResult();
        }
        [HttpPost]
        public ActionResult EditUserEditGroup_GetNewGroup(int? userId)
        {
            ViewBag.GroupList = facade.GetAvaliableGroupsForUser((int) userId); 
            
            return View("pAddNewGroupToUser");
        }
        [HttpPost]
        public JsonResult DeleteUser(int id)
        {
            facade.RemoveUser(id);
            return new JsonResult();
        }

//        public ActionResult Users()
//        {
//            ViewBag.users = GetPeople();
//            return View();
//        }
//        public ActionResult Group(int? id)
//        {
//            GroupModel groupModel;
//            if (id != null)
//                groupModel = wne.core.Class1.GetGroupById(id.Value);
//            else
//            {
//                groupModel = wne.core.Class1.GetGroupById(-1);
//                groupModel.SelectedParents = new Dictionary<int, string>();
//                groupModel.Fields = new List<FieldModel>();
//            }
//            return View(groupModel);
//        }

//        //[HttpGet]
//        //public ActionResult Group(int id)
//        //{
//        //var GroupModel = new GetGroupById(id); // Верный ли метод я указал?
//        //return View(GroupModel);
//        //}
//        [HttpPost]
//        public ActionResult Group(FormCollection qqq)
//        {
//            var id = qqq["groupId"];
//            if (id == "0")
//                id = null;
//            var name = qqq["groupName"];
//            string currentParents = "";
//            if (qqq["groupParentOne"] != null) currentParents = currentParents + qqq["groupParentOne"] + ";";
//            if ((qqq["parentDDL"] != null) && (qqq["parentDDL"].IndexOf(",") != -1))
//                currentParents = qqq["parentDDL"].Substring(qqq["parentDDL"].IndexOf(",") + 1);
//            var fieldNames = qqq["fieldName"];
//            var fieldTypes = qqq["fieldType"];
//            var fieldCanEdit = qqq["fieldCanEdit"];
//            var fieldMandatory = qqq["fieldMandatory"];
//            var fieldVarValues = qqq["fieldVarValues"];
//            models.GroupModel model = wne.core.Class1.UpdateOrAddGroup(id, name, currentParents, fieldNames, fieldTypes,
//                fieldCanEdit, fieldMandatory, fieldVarValues);
//            return Redirect("/Admin/User_groups");
//        }



//        public ActionResult User_Groups()
//        {
//            var AllGroup = wne.core.Class1.GetAllGroups(1);
//            ViewBag.XUY = 1;
//            return View(AllGroup);
//        }
//        [HttpPost]
//        public ActionResult User_Groups(FormCollection qqq)
//        {
//            var FieldSearch = qqq["FieldSearch"];
//            var SortOrder = qqq["SortOrder"];
//            var AllGroup = new List<GroupSmallModel>();//=wne.core.Class1.GetAllGroups(SortOrder,FieldSearch);
//            ViewBag.XUY = int.Parse(SortOrder);
//            return View(wne.core.Class1.GetAllGroups(int.Parse(SortOrder)));
//        }

//        [HttpGet]
//        public RedirectResult DeleteGroup(int id)
//        {
//            wne.core.Class1.DeleteGroupByIdWithoutChild(id);
//            return Redirect("/Admin/User_Groups");
//        }
//        public ActionResult View1()
//        {
//            var c = new Dictionary<int, string> { { 10, "qqq" } };
//            var model = new TestModel
//            {
//                book = new List<Books>
//                {
//                    new Books
//                    {
//                        id = 10, list = new Dictionary<int, string>{{10,"qqq"},{20,"ccc"}},
//                        qqq = new List<CheckBox>
//                        {
//                            new CheckBox { Text = "Fulltime", Checked = true},
//                            new CheckBox { Text = "Partly" },
//                            new CheckBox { Text = "Contract" }
//                        }
//                    },
//                    new Books
//                    {
//                        id = 10, list = new Dictionary<int, string>{{10,"qqq"},{20,"ccc"}},
//                        qqq = new List<CheckBox>
//                        {
//                            new CheckBox { Text = "Fulltime" },
//                            new CheckBox { Text = "Partly" },
//                            new CheckBox { Text = "Contract" }
//                        }
//                    }
//                }
//            };
//            return View(model);
//        }
//        [HttpPost]
//        public ActionResult View1(TestModel model)
//        {
//            return View();
//        }
//        public List<UserModel> GetPeople()
//        {
//            List<UserModel> listPeople = new List<UserModel>();

//            listPeople.Add(new UserModel("Hajan", "Selmani", "hajan@hajan.com", 070070070, DateTime.Now, 25));
//            listPeople.Add(new UserModel("Straight", "Dean", "email@address.com", 123456789, DateTime.Now.AddDays(-5), 35));
//            listPeople.Add(new UserModel("Karsen", "Livia", "karsen@livia.com", 46874651, DateTime.Now.AddDays(-2), 31));
//            listPeople.Add(new UserModel("Ringer", "Anne", "anne@ringer.org", null, DateTime.Now, null));
//            listPeople.Add(new UserModel("O'Leary", "Michael", "23sssa@asssa.org", 32424344, DateTime.Now, 44));
//            listPeople.Add(new UserModel("Gringlesby", "Anne", "email@yahoo.org", null, DateTime.Now.AddDays(-9), 18));
//            listPeople.Add(new UserModel("Locksley", "Stearns", "my@email.org", 2135345, DateTime.Now, null));
//            listPeople.Add(new UserModel("DeFrance", "Michel", "email@address.com", 235325352, DateTime.Now.AddDays(-18), null));
//            listPeople.Add(new UserModel("White", "Johnson", null, null, DateTime.Now.AddDays(-22), 55));
//            listPeople.Add(new UserModel("Panteley", "Sylvia", null, 23233223, DateTime.Now.AddDays(-1), 32));
//            listPeople.Add(new UserModel("Blotchet-Halls", "Reginald", null, 323243423, DateTime.Now, 26));
//            listPeople.Add(new UserModel("Merr", "South", "merr@hotmail.com", 3232442, DateTime.Now.AddDays(-5), 85));
//            listPeople.Add(new UserModel("MacFeather", "Stearns", "mcstearns@live.com", null, DateTime.Now, null));

//            return listPeople;
        //        }

        #endregion

        #region Routes

        public ActionResult EditRoute(int? id)
        {
            RouteModel model = new RouteModel {};
            List<GroupSmallModel> groups = new List<GroupSmallModel>();
            groups = facade.GetFilteredGroupSmall(new GroupSmallFilter
            {
                OrderEnum = (GroupSmallOrderEnum)(1 / 2),
                SearchString = ""
            });
            ViewBag.ListGroups = groups;
            if (id != null) model = facade.GetRouteById((int)id);
            return View(model);
        }

        [HttpPost]
        public ActionResult EditRoute(RouteModel model, int? RouteId, string RouteName, string RouteString)
        {
            if (RouteId != null) model.RouteId = (int)RouteId;
            model.RouteName = RouteName;
            model.RouteString = RouteString;
            var rrr = new RouteModel(model.RouteString);
            rrr.RouteName = RouteName;
            rrr.RouteString = RouteString;
            if (RouteId != null) rrr.RouteId = (int)RouteId;
            if (RouteId <= 0)
            {
                if (facade.RouteNotExists(RouteName))
                {
                    facade.CreateRoute(rrr);
                }
                else
                {
                    ViewBag.ErrMessNewRoute = "Маршрут с названием уже существует!";
                    return View(model);
                }
                
            }
            else
            {
                facade.UpdateRoute(rrr);
            }
            
            return Redirect("/Admin/RouteList");
        }



        public ActionResult RouteList()
        {
            ViewBag.orderNum = "1";
            ViewBag.searchString = "";
            RouteFilter_l filter = new RouteFilter_l();
            filter.SearchString = "";
            filter.IsOrderDesc = true;
            filter.OrderEnum = (RouteOrderEnum)1;
            return View(facade.GetFilteredRoutes(filter));
        }


        [HttpPost]
        public ActionResult RouteList(String orderNum, String searchString)
        {
            ViewBag.orderNum = orderNum;
            ViewBag.searchString = searchString;
            RouteFilter_l filter = new RouteFilter_l();
            filter.SearchString = searchString;
            filter.IsOrderDesc = ("1".Equals(orderNum)) ? true : false;
            filter.OrderEnum = (RouteOrderEnum)1;
            List<RouteModel> m = facade.GetFilteredRoutes(filter);
            return View(m);
        }

        [HttpPost]
        public JsonResult DeleteRoute(int id)
        {
            facade.DeleteRoute(id);
            return new JsonResult();
        }


        #endregion

       


    }
}
